<?php


namespace app\admin\service;


use think\facade\Cache;
use app\common\exception\ThrowException;
class Token
{
    /**
     *  验证 Token
     */
    public function check($token)
    {
        return  Cache::get($token);
    }


    /**
     *  生成Token码
     */
    public function generateToken()
    {
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('operator.token_salt');
        return sha1($randChar . $timestamp . $tokenSalt);
    }

    /**
     *  获取 授权Token
     */
    public function get($operator)
    {
        $values = [
            'operator_id' => $operator->id,
            'cname' => $operator->cname,
            'isadmin' => $operator->isadmin,
            'phone' => $operator->phone,
            'email' => $operator->email,
            'roles' => $operator->roles
        ];

        return self::saveToCache($values);
    }


    private function saveToCache($values){

        $token = self::generateToken();
        $expire_in = config('operator.token_expire_in');
        $result = cache($token, json_encode($values), $expire_in);

        if(!$result){
            throw new ThrowException([
                'msg' => '服务器缓存异常',
                'errorCode' => 0
            ]);
        }
        return $token;
    }
}
